package com.example.jwttoken.controller;

import com.example.jwttoken.pojo.User;
import com.example.jwttoken.service.UserService;
import com.example.jwttoken.target.PassToken;
import com.example.jwttoken.target.UserLoginToken;
import com.example.jwttoken.utils.JwtHelper;
import org.json.JSONException;
import org.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.Map;

@RestController
@RequestMapping("api")
public class UserApi {
    @Autowired
    UserService userService;

    //登录
    @PostMapping("/login")
    @PassToken
    public Map login(User user) throws JSONException {
        Map jsonObject=new HashMap<>();
        User userForBase=userService.findByUsername(user);
        if(userForBase==null){
            jsonObject.put("message","登录失败,用户不存在");
            return jsonObject;
        }else {
            if (!userForBase.getPassword().equals(user.getPassword())){
                jsonObject.put("message","登录失败,密码错误");
                return jsonObject;
            }else {
                String token = JwtHelper.createJWT(user);
                jsonObject.put("token", token);
                jsonObject.put("user", userForBase);
                return jsonObject;
            }
        }
    }
    @UserLoginToken
    @GetMapping("/getMessage")
    public String getMessage(){
        return "你已通过验证";
    }
}